<template>
  <view class="page">
    <!-- 头部 start-->
    <view class="cu-custom bg-white" :style="[{ height: CustomBar + 'px', paddingTop: StatusBar + 'px' }]">
      <view class="cu-bar bg-white fixed solid-bottom" :style="[{ height: CustomBar + 'px', paddingTop: StatusBar + 'px' }]">
        <view class="action" @tap="back"><text class="cuIcon-back"></text></view>
        <view class="search-form round">
          <!-- placeholder的值应该是动态的，但是跳转过来的时候没有传递任何参数，暂时砍掉这个需求 -->
          <input
            class="search-input"
            confirm-type="search"
            type="text"
            v-model="keyword"
            :maxlength="50"
            :focus="true"
            :adjust-position="false"
            :hold-keyboard="false"
            :placeholder="placeholder"
            placeholder-class="placeholderStyle"
            @confirm="handleSearch"
          />
          <text v-if="keyword.length != 0" class="cuIcon-close text-gray padding-right-xs" @tap="clear"></text>
        </view>
        <view class="right padding-right" @click="handleSearch"><text class="cuIcon-search" style="font-size: 36rpx;"></text></view>
      </view>
    </view>
    <!-- 头部 end-->
    <!-- 历史,热搜 -->
    <view v-if="words.length == 0" class="wrap-box padding-sm">
      <!-- 搜索历史 start-->
      <view>
        <view class="padding-bottom-sm flex justify-between align-center">
          <text class="text-lg text-333">{{ i18n['历史搜索'] }}</text>
          <view><text v-if="history_list.length != 0" class="cuIcon-delete text-666 text-lg" @tap="clearHistory"></text></view>
        </view>
        <view class="history-list" v-if="history_list.length != 0">
          <block v-for="(item, index) in history_list" :key="index">
            <view class="history-tag" @click="handleSearch($event, item,index)" @longpress="handleLongpress(index)">
              {{ item }}
              <text v-if="index == removeIndex" class="close cuIcon-close"></text>
            </view>
          </block>
        </view>
        <view v-else class="text-666 text-sm margin-bottom margin-top-xs">{{i18n['暂无历史记录']}}</view>
      </view>
      <!-- 搜索历史 end-->
      <!-- 搜索发现 start-->
      <view v-if="search_found.length != 0">
        <view class="padding-bottom-sm flex justify-between align-center">
          <text class="text-lg text-333">{{ i18n['搜索发现'] }}</text>
        </view>
        <view class="history-list">
          <block v-for="(item, index) in search_found" :key="index">
            <view class="history-tag" v-if="index < 10" @tap="toClassify(item)">{{ item }}</view>
          </block>
        </view>
      </view>
      <!-- 搜索发现 end-->
    </view>
    <!--推荐商品 -->
    <view v-if="words.length == 0" class="fu-recommend-box">
      <view class="padding-left-sm text-lg text-333 margin-bottom">{{ i18n['推荐商品'] }}</view>
      <fu-waterflow :showTitle="false" ref="guess" mode="simple"></fu-waterflow>
    </view>
    <!-- 断网检测组件 -->
    <fu-notwork></fu-notwork>
  </view>
</template>

<script>
export default {
  data() {
    return {
      localSearchHistory: [], // 本地历史搜索记录表
      keyword: '', // 搜索关键字
      history_list: [], // 历史记录表
      removeIndex: -1, // 要删除的下标
      words: [], // 搜索联想分词表
      placeholder: global.i18n['搜索你想要的商品'],
      listenerType: 'listener', // 是否识别成功 listener success fail
      listenerWord: '', // 语音识别的文字
      keyboardheight: 0, // 键盘高度
      isFind: true, // 是否展示搜索发现
      findData: [], // 热搜榜
      search_found: [], //热搜发现
      tabindex: 0, // tab初始值
      search_info: {}, //搜索信息
      isInit: false, // 初始化数据信息
      current: 0, // 榜单tab切换
      hotSerchList: [] // 热销榜
    };
  },
  onShow() {
    this.removeIndex = -1;
    this.initHistory();
    this.words = [];
  },
  onLoad(options) {
    this.search_info = options;
    if (options) {
      this.placeholder = options.name || this.i18n['搜索你想要的商品'];
    }
    // 监听键盘事件
    uni.onKeyboardHeightChange(res => {
      this.keyboardheight = res.height;
    });
    this.$nextTick(() => {
      setTimeout(() => {
        this.$refs.guess && this.$refs.guess.refresh();
      }, 300);
    });
  },
  onReachBottom() {
    this.$refs.guess && this.$refs.guess.loadData();
  },
  methods: {
    // 清除历史记录弹窗
    clearHistory() {
      this.$util.showModal({
        title: this.i18n["提示"],
        content: this.i18n['确定删除历史记录？'],
        confirmColor: this.$store.state.themeColor,
        success: res => {
          if (res.confirm) {
            this.clearAllHistory();
          }
        }
      });
    },
    // 清除历史记录
    clearAllHistory() {
      this.history_list = [];
      uni.clearStorageSync('SEARCHHISTORY');
    },
    // 长按事件
    handleLongpress(index) {
      this.removeIndex = index;
    },
    // 删除单个历史记录
    removeHistory(keyword) {
      console.log('删除历史搜索', keyword);
      this.history_list = this.history_list.filter(ele => ele != keyword);
      uni.setStorageSync('SEARCHHISTORY', this.history_list);
    },
    /**
     * @description 搜索
     * @param {Object} e 事件源对象
     * @param {Object} item 商品信息
     */
    handleSearch(e, item,index) {
      uni.hideKeyboard();
      if (item) {
        if (index == this.removeIndex) {
          this.removeHistory(item);
          this.removeIndex = -1;
          return false;
        }
        console.log('搜索历史触发');
        // 点击历史记录去搜索
        this.$urouter.navigateTo({
          url: '/pages/index/search/search-list/index',
          params: {
            keyWords: item
          }
        });
      } else {
        // 搜索按钮或语音搜索
        if (this.keyword.trim() != '') {
          // 输入框触发搜索
          this.$urouter.navigateTo({
            url: '/pages/index/search/search-list/index',
            params: {
              keyWords: this.keyword
            }
          });
        } else if (this.placeholder != this.i18n['搜索你想要的商品']) {
          // 首页带过来的数据触发搜索
          this.$urouter.navigateTo({
            url: '/pages/index/search/search-list/index',
            params: {
              keyWords: this.placeholder
            }
          });
        } else {
          this.$message.info(this.i18n['请输入搜索关键字']);
        }
        this.keyword = '';
        this.keyboardheight = 0;
      }
    },
    /**
     * @description 去商品列表页面
     * @param {String} item 商品关键词信息
     */
    toClassify(item) {
      this.keyword = item;
      this.handleSearch();
    },
    /**
     * @func 后退
     */
    back() {
      uni.navigateBack();
    },
    // 初始化历史记录列表
    initHistory() {
      let _data = uni.getStorageSync('SEARCHHISTORY');
      if (_data) {
        this.history_list = _data;
      }
    },
    /**
     * @func 清除输入框
     */
    clear() {
      this.keyword = '';
      this.words = [];
    }
  }
};
</script>

<style lang="scss" scoped>
// 标签样式
.history-list {
  display: flex;
  flex-wrap: wrap;
  .history-tag {
    padding: 12rpx 40rpx;
    background-color: #f8f8f8;
    margin-right: 24rpx;
    margin-bottom: 24rpx;
    border-radius: 48rpx;
    font-size: 24rpx;
    color: #333333;
    position: relative;
    .close {
      position: absolute;
      top: 50%;
      right: 10rpx;
      transform: translateY(-50%);
      font-size: 20rpx;
    }
  }
}

.page {
  width: 100%;
  min-height: 100vh;
  background-color: #ffffff;
}

.search-form {
  position: relative;
  background-color: #f9f9f9;
  .search-input {
    font-size: 24rpx;
    color: #666666;
    text-indent: 32rpx;
  }
  .placeholderStyle {
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    font-size: 24rpx;
    color: #bfbfbf;
    text-indent: 32rpx;
  }
  .close {
    position: absolute;
    right: 0;
  }
}

// 推荐
.fu-recommend-box {
  background: linear-gradient(180deg, #ffffff 0%, #ffffff 7%, #f8f8f8 34%, #f8f8f8 100%);
}
</style>
